package Components
{
	import flash.display.DisplayObject;
	
	import mx.collections.ArrayCollection;
	import mx.containers.HBox;
	import mx.core.IDataRenderer;
	import mx.events.CollectionEvent;
	import mx.events.CollectionEventKind;

	/**
	 * This class is kind of a hack, because I couldn't get the 
	 * 	HorizontalList to exhibit the behavior found here.
	 *  Namely, we want the box to expand or contract to fit its children exactly
	 */
	public class BoundHBox extends HBox
	{
		public var itemRenderer:Class;
		
		protected var unusedRenderers:ArrayCollection = new ArrayCollection();
		
		private var _dataProvider:ArrayCollection;
		public function get dataProvider():ArrayCollection
		{
			return _dataProvider;
		}
		public function set dataProvider(val:ArrayCollection):void
		{
			if(_dataProvider)
				_dataProvider.removeEventListener(CollectionEvent.COLLECTION_CHANGE, listChangeHandler);
			_dataProvider = val;
			if(_dataProvider)
				_dataProvider.addEventListener(CollectionEvent.COLLECTION_CHANGE, listChangeHandler);
		}
		
		protected function listChangeHandler(evt:CollectionEvent):void
		{
			if(evt.kind == CollectionEventKind.ADD)
			{
				var ir:DisplayObject = getItemRenderer();
				if(ir is IDataRenderer)
					IDataRenderer(ir).data = evt.items[0];
				addChildAt(ir, evt.location);
			}
			else if(evt.kind == CollectionEventKind.REMOVE)
			{
				var old:DisplayObject = removeChildAt(evt.location);
				unusedRenderers.addItem(old);
			}
		}
		
		protected function getItemRenderer():DisplayObject
		{
			if(unusedRenderers.length > 0)
				return unusedRenderers.removeItemAt(0) as DisplayObject;
			else
				return new itemRenderer() as DisplayObject;
		}
	}
}